package ru.picman;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

/**
 * Handler for all sensor-events, used to implement tilt-based controls.
 * @author David
 *
 */
class PicmanOrientationHandler implements SensorEventListener
{
	float gravity[] = null;
	float geo[] = null;
	float orientation[] = null;
	
	boolean sensorsReady = false;
	
	int X = 0;
	int Y = 1;
	int Z = 2;
	
	Player player;
	
	boolean orientationSet = false;
	
	/**
	 * Constructor for the orientation handler
	 * @param player Player-object this handler will affect.
	 */
	public PicmanOrientationHandler(Player player)
	{
		this.player = player;
		
		gravity = new float[3];
		geo = new float[3];
		orientation = new float[3];
	}
	
	
	public void resetOrientation()
	{
		orientationSet = false;
	}
	
	public void onAccuracyChanged(Sensor sensor, int accuracy) 
	{
		// TODO Auto-generated method stub
		
	}
	
	public static float RADIANS = 57.2957795f;
	
	private static final int TILT_THRESHOLD = 15;
	
	
	public void onSensorChanged(SensorEvent event) 
	{
		switch(event.sensor.getType())
		{
		case Sensor.TYPE_ACCELEROMETER:
			gravity = event.values.clone();
			break;
			
		case Sensor.TYPE_MAGNETIC_FIELD:
			geo = event.values.clone();
			sensorsReady = true;
			break;
		}
		
		if(sensorsReady && gravity != null && geo != null)
		{
			float rotationMatrix[] = new float[16];
			float currentOrientation[] = new float[3];
			
			SensorManager.getRotationMatrix(rotationMatrix, null, gravity, geo);
			SensorManager.getOrientation(rotationMatrix, currentOrientation);
			
			if(!orientationSet)
			{
				orientation = currentOrientation.clone();
				orientationSet = true;
			}
			
			else
			{
				if(Math.abs(currentOrientation[2] - orientation[2]) > Math.abs(currentOrientation[1] - orientation[1]))
				{
					if(currentOrientation[2] * RADIANS - orientation[2] * RADIANS < -TILT_THRESHOLD)
						player.getUnit().setDesiredDirection(Unit.DIRECTION_UP);
						
					else if(currentOrientation[2] * RADIANS - orientation[2] * RADIANS > TILT_THRESHOLD)
						player.getUnit().setDesiredDirection(Unit.DIRECTION_DOWN);
				}
				
				else
				{
					if(currentOrientation[1] * RADIANS - orientation[1] * RADIANS < -TILT_THRESHOLD)
						player.getUnit().setDesiredDirection(Unit.DIRECTION_LEFT);
					
					else if(currentOrientation[1] * RADIANS - orientation[1] * RADIANS > TILT_THRESHOLD)
						player.getUnit().setDesiredDirection(Unit.DIRECTION_RIGHT);
				}
				//orientation = currentOrientation.clone();
			}

		}
		
		
		
	}
};